<?php

include_once('config/config.php');

$action = $_POST['action'] ?? '';

$adminId = $_POST['adminId'] ?? '';

$adminSql = "SELECT id FROM `pre_admin` WHERE `id` = '$adminId'";

$admin = find($adminSql);

if (!$admin) {
	error('请先登录');
	exit();
}

if ($action === 'dep') {
	$depSql = "SELECT * FROM `pre_department` ORDER BY `id` DESC";
	$DepData = all($depSql);
	if ($DepData) {
		success('查询部门数据成功', $DepData);
	} else {
		error('暂无数据');
	}
}

if ($action === 'job') {
	$depId = $_POST['depId'] ?? 0;

	$jobSql = "SELECT * FROM `pre_job` WHERE `depid` = '$depId'";
	$JobData = all($jobSql);
	if ($JobData) {
		success('查询职位数据成功', $JobData);
	} else {
		error('暂无数据');
	}
}

if ($action === 'del') {
	$id = $_POST['id'] ?? 0;
	$table = $_POST['table'] ?? '';

	if ($table === 'person') {
		$personSql = "SELECT `id` FROM `pre_person` WHERE `id` = '$id'";
		$person = find($personSql);
		if (!$person) {
			error('员工不存在');
			exit();
		}
		$result = del($table, "`id` = '$id'");
		if ($result['code'] === 0) {
			error($result['msg']);
		} else {
			@is_file('./upload/' . $person['avatar']) && @unlink('./upload/' . $person['avatar']);
			success('删除成功');
		}
	}

	if ($table === 'admin') {
		$adminSql = "SELECT `id`,`avatar` FROM `pre_admin` WHERE `id` = '$id'";
		$admin = find($adminSql);
		if (!$admin) {
			error('管理员不存在');
			exit();
		}
		$result = del($table, "`id` = '$id'");
		if ($result['code'] === 0) {
			error($result['msg']);
		} else {
			@is_file('./upload/' . $admin['avatar']) && @unlink('./upload/' . $admin['avatar']);
			success('删除成功');
		}
	}

	if ($table === 'department') {
		$depSql = "SELECT `id` FROM `pre_department` WHERE `id` = '$id'";
		$dep = find($depSql);
		if (!$dep) {
			error('部门不存在');
			exit();
		}
		$result = del($table, "`id` = '$id'");
		if ($result['code'] === 0) {
			error($result['msg']);
		} else {
			success('删除成功');
		}
	}

	if ($table === 'job') {
		$jobSql = "SELECT `id` FROM `pre_job` WHERE `id` = '$id'";
		$job = find($jobSql);
		if (!$job) {
			error('职位不存在');
			exit();
		}
		$result = del($table, "`id` = '$id'");
		if ($result['code'] === 0) {
			error($result['msg']);
		} else {
			success('删除成功');
		}
	}
}